export default {
	namespaced: true,
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations:{
		addToCart(state, goods) {
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
			if(!findResult) {
				state.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		updateGoodsState(state, val) {
			const findResult = state.cart.find((x) => x.goods_id === val.goods_id)
			findResult.goods_state = val.goods_state
			this.commit('m_cart/saveToStorage')
		},
		updateGoodsCount(state, val) {
			const findResult = state.cart.find((x) => x.goods_id === val.goods_id)
			if(findResult) {
				findResult.goods_count = val.goods_count
				this.commit('m_cart/saveToStorage')
			}
		}, 
		removeGoodsByID(state, goods_id) {
			state.cart = state.cart.filter(x => x.goods_id != goods_id)
			this.commit('m_cart/saveToStorage')
		},
		selectAll(state, isAllSelected) {
			if(isAllSelected) {
				state.cart.forEach(x => x.goods_state = true)
			} else {
				state.cart.forEach(x => x.goods_state = false)
			}
		}
	},
	getters: {
		total(state) {
			let num = 0
			state.cart.forEach(x => num += x.goods_count)
			return num
		},
		checkedTotal(state) {
			let num = 0
			const checkedList = state.cart.filter(x => x.goods_state === true)
			checkedList.forEach(x => num += x.goods_count)
			return num
		},
		checkedCount(state) {
			let totalmoney = 0
			const checkedList = state.cart.filter(x => x.goods_state === true)
			checkedList.forEach(x => totalmoney += x.goods_count*x.goods_price)
			return totalmoney.toFixed(2)
		},
		isAll(state) {
			for(let i=0; i < state.cart.length; i++) {
				if(!state.cart[i].goods_state) return false
			}
			return true
		}
	}
}